//
//  EditInfoViewController.m
//  Rabbit
//
//  Created by 阿帕 on 2018/11/19.
//  Copyright © 2018 GCY. All rights reserved.
//

#import "EditInfoViewController.h"
#import "ChangePasswordViewController.h"
#import "ChangePhoneViewController.h"
#import "CancellationAccountViewController.h"
#import "UIImage+CYCircle.h"
#import "JPUSHService.h"

@interface EditInfoViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
{
    UIImagePickerController *_ipc;//图片选择器
    NSString *_headUrl;
}
@property (weak, nonatomic) IBOutlet UIButton *headImageView;
@property (weak, nonatomic) IBOutlet UIButton *changePsdBtn;
@property (weak, nonatomic) IBOutlet UITextField *nicknameTextField;
@property (weak, nonatomic) IBOutlet UILabel *nicknameTextLabel;
@property (weak, nonatomic) IBOutlet UILabel *phoneTextLabel;
@property (weak, nonatomic) IBOutlet UILabel *changePsdTextLabel;
@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;
@property (weak, nonatomic) IBOutlet UIButton *logoutButton;
@property (weak, nonatomic) IBOutlet UIButton *saveButton;
@property (weak, nonatomic) IBOutlet UIView *hLineView;
@property (weak, nonatomic) IBOutlet UIView *hLineView2;
@property (weak, nonatomic) IBOutlet UIView *headBgView;
@property (assign, nonatomic) BOOL ifHidden;

@end

@implementation EditInfoViewController

//-(BOOL)prefersStatusBarHidden
//{
//    return self.ifHidden;
//}
//
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [DCSpeedy changeNavControllerGradientView:self andBgColor:[UIImage gradientImageWithBounds:self.navigationController.view.bounds andColors:@[Theme_ColorValue, Theme_ColorValue] andGradientType:GradientDirectionRightToLeft] andTitleColor:[UIColor whiteColor]];
    
    UIButton *button = [[UIButton alloc] init];
    [button setImage:[UIImage imageNamed:@"gcy_img_nav_lArrowTwo"] forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 0, 17, 32);
    [button addTarget:self action:@selector(backButtonTapClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = backItem;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    //    [DCSpeedy changeNavControllerGradientView:self andBgColor:[UIImage imageWithColor:[UIColor whiteColor]] andTitleColor:Dark_TextColor];
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    //    self.ifHidden = YES;
    //    if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) {
    //        [self prefersStatusBarHidden];
    //        [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
    //    }
    //    UIView *statusBarView = [[UIView alloc]   initWithFrame:CGRectMake(0, 0,  ScreenW, 50)];
    //    UILabel *errorMsgLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0,  ScreenW, 50)];
    //    errorMsgLabel.textAlignment = NSTextAlignmentCenter;
    //    errorMsgLabel.textColor = [UIColor whiteColor];
    //    errorMsgLabel.text = @"密码错误";
    //    [statusBarView addSubview:errorMsgLabel];
    //    statusBarView.backgroundColor =  [UIColor colorWithRed:253/255.0 green:172/255.0 blue:5/255.0 alpha:1/1.0];
    //    statusBarView.layer.position = CGPointMake(0, 0);
    //    statusBarView.layer.anchorPoint = CGPointMake(0,0);
    //    [self.navigationController.navigationBar addSubview:statusBarView];
    
    self.navigationItem.title = @"个人信息";
    
    self.view.backgroundColor = BackgroundColor;
    
    UIButton *resetButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [resetButton setTitle:@"注销" forState:UIControlStateNormal];
    resetButton.titleLabel.font = font(15);
    [resetButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [resetButton addTarget:self action:@selector(rightBarItemClick) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:resetButton];
    rightItem.imageInsets = UIEdgeInsetsMake(0, -15,0, 0);//设置向左偏移
    self.navigationItem.rightBarButtonItem = rightItem;
    
    _headBgView.cy_width = ScreenW;
    UIImage *backImage = [UIImage gradientImageWithBounds:_headBgView.bounds andColors:@[Theme_ColorValue, Theme_ColorValue] andGradientType:GradientDirectionRightToLeft];
    UIColor *blueColor = [UIColor colorWithPatternImage:backImage];
    [_headBgView setBackgroundColor:blueColor];
    
    [DCSpeedy dc_setUpBezierPathCircularLayerWithControl:_headImageView size:_headImageView.size];
    
    _nicknameTextField.textColor = Dark_TextColor;
    _nicknameTextLabel.textColor = Dark_TextColor;
    _phoneTextLabel.textColor = Dark_TextColor;
    _changePsdTextLabel.textColor = Dark_TextColor;
    _phoneLabel.textColor = Dark_TextColor;
    _hLineView.backgroundColor = BackgroundColor;
    _hLineView2.backgroundColor = BackgroundColor;
    [_changePsdBtn setTitleColor:Light_TextColor forState:UIControlStateNormal];
    
    //    cutBorder(_logoutButton, 1, @"#2D7DF6");
    [_logoutButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    _saveButton.hidden = YES;
    //    [_saveButton setBackgroundColor:Theme_ColorValue];
    //    cut(_saveButton, BTN_BORDER_RADIUS);
    
    cut(_logoutButton, BTN_BORDER_RADIUS);
    [_logoutButton setBackgroundColor:Theme_ColorValue];
    
    
    NSDictionary *userInfo = [UserDefaultUtil valueForKey:Login_Branch];
    
    _phoneLabel.userInteractionEnabled = YES;
    [_phoneLabel nyl_addTapGes:^{
        
        if ([[UserDefaultUtil valueForKey:DRIVER_TYPE] integerValue] == 2) {
            [XSInfoView showInfo:@"车队司机不能修改手机号" onView:self.view];
            return;
        }
        
//        if ([[UserDefaultUtil valueForKey:DRIVER_TYPE] integerValue] == 0 && [[userInfo valueForKey:@"joinTeam"] integerValue] == 1) {
//            [XSInfoView showInfo:@"已加入车队不能修改手机号" onView:self.view];
//            return;
//        }
        
        ChangePhoneViewController *cpvc = [[ChangePhoneViewController alloc] init];
        cpvc.oldPhone = _infoDic[@"phone"];
        [self.navigationController pushViewController:cpvc animated:YES];
        
    }];
    
    [self getPersonInfoRequest];
}

#pragma mark - 我的信息拉取
- (void)getPersonInfoRequest {
    
    [_headImageView setBackgroundImageWithURL:[NSURL URLWithString:_infoDic[@"headImg"]] forState:UIControlStateNormal placeholder:image(@"gcy_img_my_defultHead")];
    _nicknameTextField.text = _infoDic[@"name"];
    _phoneLabel.text = _infoDic[@"phone"];
    _headUrl = _infoDic[@"headImg"];
    
}

- (IBAction)btnClickEvent:(UIButton *)sender {
    WEAKSELF
    if (sender.tag == 100) {
        //换头像
        _ipc = [[UIImagePickerController alloc] init];
        _ipc.delegate = self;
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            _ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
            _ipc.showsCameraControls = YES;
            [self presentViewController:_ipc animated:YES completion:nil];
            
        }];
        
        UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"我的相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            _ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:_ipc animated:YES completion:nil];
            
        }];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertController addAction:cameraAction];
        [alertController addAction:photoAction];
        [alertController addAction:cancelAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else if (sender.tag == 101) {
        
        ChangePasswordViewController *cpvc = [[ChangePasswordViewController alloc] init];
        [self.navigationController pushViewController:cpvc animated:YES];
        
    } else if (sender.tag == 102) {
        
        if ([DCSpeedy isBlankString:_nicknameTextField.text] == YES) {
            [XSInfoView showInfo:@"姓名不能为空" onView:self.view];
            return;
        }
        
        //保存
        NSDictionary *params = @{
            @"name": _nicknameTextField.text,
            @"headImg": _headUrl,
            @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
        };
        
        [HTTPManager postNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], PARTY_UPDATEME) withParameter:params withVC:self netName:@"修改个人信息" success:^(id response, NSString *msg) {
            
            [XSInfoView showInfo:@"修改信息成功" onView:self.view];
            
            [KNotificationCenter postNotificationName:LOGIN_SUCCESS object:nil];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
            
        } failure:^(NSInteger code, NSString *msg) {
            
        }];
        
    } else if (sender.tag == 103) {
        //退出当前账号
        [DCSpeedy dc_SetUpAlterWithView:self Title:@"" Message:@"确定退出当前账号吗？" Sure:^{
            
            [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], LOGOUT) withParameter:@{ @"token":[UserDefaultUtil valueForKey:USER_TOKEN],} withVC:self netName:@"退出登录" success:^(id response, NSString *msg) {
                
                [UserDefaultUtil saveValue:@"" forKey:USER_TOKEN];
                
                [KNotificationCenter postNotificationName:LOGIN_LOGOUT object:@{}];
                
                [KNotificationCenter postNotificationName:@"AuthOverdue" object:nil];
                
                [XSInfoView showInfo:@"退出登录成功" onView:weakSelf.view];
                
                //清空极光标签
                [JPUSHService cleanTags:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
                    DebugLog(@"清空极光标签 %tu,%@,%tu",iResCode,iTags,seq);
                } seq:1];
                //删除极光别名
                [JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
                    DebugLog(@"删除极光别名 %tu,%@,%tu",iResCode,iAlias,seq);
                } seq:1];
                
                [DCSpeedy removeLocationNotice];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                });
                
            } failure:^(NSInteger code, NSString *msg) {
                
            }];
            
        } Cancel:^{
            
        }];
        
    }
    
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    //判断媒体资源类型，（图片或者是视频）
    NSString *imageType = [info objectForKey:UIImagePickerControllerMediaType];
    UIImage *gerenimage = [[UIImage alloc] init];
    //如果是图片资源
    if ([imageType isEqualToString:(NSString *)kUTTypeImage]) {
        //取到从系统图片库选择的图片或者照相机拍摄的图片
        if (_ipc.sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
            gerenimage = [info objectForKey:UIImagePickerControllerOriginalImage];
        }else if(_ipc.sourceType == UIImagePickerControllerSourceTypeCamera){
            gerenimage = [info objectForKey:UIImagePickerControllerOriginalImage];
        }
        UIImageOrientation imageOrientation = gerenimage.imageOrientation;
        if(imageOrientation!=UIImageOrientationUp)
        {
            // 原始图片可以根据照相时的角度来显示，但UIImage无法判定，于是出现获取的图片会向左转９０度的现象。
            // 以下为调整图片角度的部分
            UIGraphicsBeginImageContext(gerenimage.size);
            [gerenimage drawInRect:CGRectMake(0, 0, gerenimage.size.width, gerenimage.size.height)];
            gerenimage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            // 调整图片角度完毕
        }
        
    }
    
    
    NSMutableArray *muArr = [[NSMutableArray alloc] init];
    [muArr addObject:gerenimage];
    
    //发送头像请求
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [HTTPManager postUploadFiles:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-tps-api",[ReAddressDynamic shared].baseUrl], FILE_UPLOAD) file:muArr fileName:@"file" withVC:self netName:@"头像上传" success:^(id response, NSString *msg) {
            
            [_headImageView sd_setBackgroundImageWithURL:[NSURL URLWithString:response[@"data"]] forState:UIControlStateNormal];
            
            //            _headUrl = response[@"data"];
            
            //保存
            NSDictionary *params = @{
                @"name": _nicknameTextField.text,
                @"headImg": response[@"data"],
                @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
            };
            
            [HTTPManager postNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], PARTY_UPDATEME) withParameter:params withVC:self netName:@"修改个人信息" success:^(id response, NSString *msg) {
                
                [XSInfoView showInfo:@"修改头像成功" onView:self.view];
                
                [KNotificationCenter postNotificationName:LOGIN_SUCCESS object:nil];
                
            } failure:^(NSInteger code, NSString *msg) {
                
            }];
            
        } failure:^(NSInteger code, NSString *msg) {
            
        }];
    });
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)rightBarItemClick {
    //注销
    CancellationAccountViewController *cavc = [[CancellationAccountViewController alloc] init];
    cavc.phoneNum = _infoDic[@"phone"];
    [self.navigationController pushViewController:cavc animated:YES];
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    
    //更改picker的导航条颜色 及item的tintcolor
    if ([_ipc.navigationBar respondsToSelector:@selector(setBarTintColor:)]) {
        _ipc.navigationBar.tintColor = [UIColor cy_colorWithHexString:@"484848"];
        _ipc.navigationBar.translucent = NO;
        _ipc.navigationBar.barTintColor = [UIColor whiteColor];
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
        
        //设置导航标题的属性
        [_ipc.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor cy_colorWithHexString:@"484848"], NSFontAttributeName: [UIFont systemFontOfSize:18]}];
        //        _ipc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;//弹出模式
        _ipc.allowsEditing = YES;
    }
    
}

- (void)backButtonTapClick {
    [self.navigationController popViewControllerAnimated:YES];
}

@end
